package com.it.schoolbookshop_back.controller;

import com.it.schoolbookshop_back.entities.dto.ReportRequestDTO;
import com.it.schoolbookshop_back.entities.po.Report;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.service.ReportService;
import com.it.schoolbookshop_back.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 举报相关控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/reports")
public class ReportsController {
    
    @Autowired
    private ReportService reportService;
    
    /**
     * 获取当前用户的举报记录
     * 
     * @return 举报记录列表
     */
    @GetMapping
    public Result<Map<String, Object>> getUserReports() {
        // 从Token中获取当前用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        try {
            List<Report> reports = reportService.getReportsByReporterId(userId);
            
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("reports", reports);
            
            return Result.success(resultMap);
        } catch (Exception e) {
            log.error("获取用户举报记录失败", e);
            return Result.failed("获取举报记录失败：" + e.getMessage());
        }
    }

    /**
     * 提交举报
     * 
     * @param reportRequest 举报请求数据
     * @return 举报结果
     */
    @PostMapping
    public Result<Object> submitReport(@RequestBody ReportRequestDTO reportRequest) {
        // 从Token中获取当前用户ID
        Integer reporterId = UserContext.getUserId();
        if (reporterId == null) {
            return Result.unauthorized();
        }

        try {
            // 创建举报实体
            Report report = new Report();
            report.setReporterId(reporterId);
            report.setReportedId(reportRequest.getReported_id());
            report.setBookId(reportRequest.getBook_id());
            report.setReason(reportRequest.getReason());
            report.setDetails(reportRequest.getDetails());
            report.setStatus("pending");

            // 保存举报记录
            boolean success = reportService.createReport(report);
            if (success) {
                log.info("用户{}提交举报成功，被举报人：{}，图书：{}", 
                    reporterId, reportRequest.getReported_id(), reportRequest.getBook_id());
                return Result.success("举报成功", new HashMap<>());
            } else {
                log.error("用户{}提交举报失败", reporterId);
                return Result.failed("举报失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("提交举报失败", e);
            return Result.failed("举报失败：" + e.getMessage());
        }
    }
}
